package com.action.ui.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.action.childbase.ChildBaseFragment;
import com.action.entity.HistoryStock;
import com.action.entity.event.TaskNewEvent;
import com.action.service.pressenter.MemberPressenter;
import com.action.ui.activity.user.HistoryStockPriceActivity;
import com.action.ui.activity.user.StockCountActivity;
import com.action.ui.activity.user.WithdrawDepositActivity;
import com.action.ui.view.MatchWebView;
import com.action.ui.view.NumberScrollTextView;
import com.action.ui.view.graph.Line;
import com.action.ui.view.graph.LinePoint;
import com.base.app_core.model.Paginated;
import com.base.app_core.service.pressenter.XYBUPressenter;
import com.base.app_core.service.user.model.HomeRxBean;
import com.base.app_core.service.user.model.User;
import com.base.app_core.service.user.model.UserAccount;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.XYBAUtils;
import com.base.app_core.util.log.F;
import com.blankj.utilcode.util.StringUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.hwangjr.rxbus.Bus;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.thread.EventThread;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.map.lib.util.StringUtil;
import com.xinglai.yun.R;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class PacketFragment extends ChildBaseFragment<MemberPressenter> {

    private static final int REFRESH_ACCOUNT = 999;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

//    @BindView(R.id.user_account)
//    NumberScrollTextView userAccountView;

    @BindView(R.id.headContainer)
    ConstraintLayout headerContainer;



    @BindView(R.id.tv_acount)
    NumberScrollTextView tvAcount;

    @BindView(R.id.tv_gu_price)
    NumberScrollTextView tvGuPrice;

    @BindView(R.id.tv_gu_num)
    NumberScrollTextView tvGuNum;

    @BindView(R.id.line_chart)
    LineChart lineView;

    @BindView(R.id.webView)
    MatchWebView webView;

    @BindView(R.id.taskHint)
    ImageView taskHint;

    @BindView(R.id.ll_chart)
    LinearLayout llChart;

    @Inject
    User user;

    @Inject
    UserAccount userAccount;

    @Inject
    XYBUPressenter XYBUPressenter;

    private String stockPrice = "0";

    private boolean isStop = false;

    public PacketFragment() {
    }

    @OnClick(R.id.chronometer)
    public void onClickViewStockInfo() {
        startActivity(new Intent(getActivity(), HistoryStockPriceActivity.class));
    }

    @OnClick(R.id.btnViewStockCount)
    public void onClickViewStockCount() {
        startActivity(new Intent(getActivity(), StockCountActivity.class));
    }

    @OnClick(R.id.btndesposit)
    public void onClickDesposit() {
        startActivity(new Intent(getActivity(), WithdrawDepositActivity.class));
    }

    @Override
    protected boolean isNeedShowLoading() {
        return false;
    }

    @Override
    protected boolean needShowError() {
        return false;
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    DecimalFormat percentDf = new DecimalFormat("######0.000");

    private void updateView() {
        if (StringUtil.isEmpty(userAccount.getAccount())) {
            userAccount.setAccount("0.00000000");
        }

        double hper = 0;
        if (!StringUtil.isEmpty(userAccount.getHistoryIncrease())) {
            try {
                hper = Double.parseDouble(userAccount.getHistoryIncrease());
                hper *= 100;
            } catch (Exception e) {

            }
        }

        percentDf.setRoundingMode(RoundingMode.DOWN);

        double tper = 0;
        if (!StringUtil.isEmpty(userAccount.getTodayIncrease())) {
            try {
                tper = Double.parseDouble(userAccount.getTodayIncrease());
                tper *= 100;
            } catch (Exception e) {

            }
        }
    }

    @Override
    protected void initView() {
        super.initView();
        webView.loadUrl(AppConstants.SERVER_URL + "index/role");
        XYBAUtils.strongFoucus(headerContainer);
        RxBus.get().register(PacketFragment.this);
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                mPresenter.fetchHistoryStockPrice();
            }
        }, 2000);
        initStockView(userAccount);
        if (null != user && user.getTaskUnRevice()) {
            taskHint.setVisibility(View.VISIBLE);
        } else {
            taskHint.setVisibility(View.GONE);
        }

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                XYBUPressenter.fetchUserAccount();
                if (refreshlayout != null) {
                    refreshlayout.finishRefresh(1500);
                }
            }
        });
        XYBUPressenter.attachView(this);
        // 发送消息
        sendMessagePacket();
    }

    private void sendMessagePacket() {
        setDelayMuti(1);
        handler.removeMessages(REFRESH_ACCOUNT);
        handler.sendEmptyMessageDelayed(REFRESH_ACCOUNT, AppConstants.Const.REFRESH_TIME_INIT);
    }

    private long delayMuti = 1;
    protected Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != msg)
                switch (msg.what) {
                    case REFRESH_ACCOUNT:
                        XYBUPressenter.fetchUserAccount();
                        handler.sendEmptyMessageDelayed(REFRESH_ACCOUNT, AppConstants.Const.REFRESH_TIME * getDelayMuti());
                        delayMuti++;
                        F.w("时间延迟===>" + delayMuti);
                        break;
                    default:
                        break;
                }
        }
    };

    public long getDelayMuti() {
        return delayMuti;
    }

    public void setDelayMuti(long delayMuti) {
        this.delayMuti = delayMuti;
    }

    @Override
    public void onHiddenChanged(final boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && handler != null) {
            sendMessagePacket();
        } else {
            stopHandle();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        stopHandle();
    }

    private void stopHandle() {
        setDelayMuti(1);
        handler.removeMessages(REFRESH_ACCOUNT);
    }

    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        if (object instanceof Collection) {
            if (tClass == HistoryStock.class) {
                final List<HistoryStock> o = (List<HistoryStock>) object;
                if (XYBAUtils.isEmpty(o)) {
                    llChart.setVisibility(View.GONE);
                    return;
                }

                if (o.size() == 1 && "0.010000".equals(o.get(0).getStokePrice())) {
                    llChart.setVisibility(View.GONE);
                    return;
                }

                llChart.setVisibility(View.VISIBLE);
                lineView.setVisibility(View.VISIBLE);
                Collections.sort(o, new Comparator<HistoryStock>() {
                    @Override
                    public int compare(HistoryStock o1, HistoryStock o2) {
                        return o1.getPriceDate().compareTo(o2.getPriceDate());
                    }
                });


                Line line = new Line();
                for (int i = 0; i < o.size(); i++) {
                    HistoryStock historyStock = o.get(i);
                    line.addPoint(new LinePoint(historyStock.getPriceDate(), Float.parseFloat(historyStock.getStokePrice())));
                }

                ArrayList<String> dayList = new ArrayList<>();
                ArrayList<String> stock = new ArrayList<>();
                for (HistoryStock h : o) {
                    dayList.add(h.getPriceDate());
                    stock.add(h.getStokePrice());
                }

                try {
                    final String[] quarters = dayList.toArray(new String[dayList.size()]);
                    IAxisValueFormatter formatter = new IAxisValueFormatter() {

                        @Override
                        public String getFormattedValue(float value, AxisBase axis) {
                            if ((int) value < quarters.length) {
                                return quarters[(int) value];
                            } else {
                                return "";
                            }
                        }
                    };
                    lineView.setVisibility(View.VISIBLE);
                    lineView.setDescription(null);
                    lineView.setNoDataText("暂无数据");
                    lineView.getLegend().setEnabled(false);
                    lineView.setVisibleXRangeMaximum(2);
                    lineView.setVisibleYRangeMinimum(10f, YAxis.AxisDependency.LEFT);
                    lineView.setAlpha(1.0f);
                    lineView.setBackgroundColor(Color.WHITE);
                    lineView.setBorderColor(Color.rgb(0, 0, 0));
                    lineView.setGridBackgroundColor(R.color.transparent);
                    lineView.setTouchEnabled(false);
                    lineView.setDragEnabled(true);
                    lineView.setScaleEnabled(true);
                    lineView.setPinchZoom(true);

                    XAxis xl = lineView.getXAxis();
                    xl.setEnabled(true);
                    xl.setAvoidFirstLastClipping(true);
                    xl.setPosition(XAxis.XAxisPosition.BOTTOM);
                    xl.setDrawGridLines(false);
                    xl.setTextSize(12f);
                    xl.setGranularity(1f);
                    xl.setValueFormatter(formatter);
                    xl.setDrawGridLines(false);
                    xl.setDrawAxisLine(false);
                    xl.setTextColor(Color.rgb(102, 102, 102));

                    final ArrayList<Entry> entryList = new ArrayList<>();
                    for (int i = 0; i < stock.size(); i++) {
                        entryList.add(new Entry(i, Float.parseFloat(stock.get(i))));
                    }

                    lineView.getAxisRight().setEnabled(false);
                    lineView.getAxisLeft().setEnabled(false);
                    LineDataSet l1 = new LineDataSet(entryList, "红色");
                    l1.setDrawFilled(true);
                    l1.setFillDrawable(new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM,
                            new int[]{Color.rgb(244, 244, 244), Color.rgb(244, 244, 244)}));
                    l1.setLineWidth(2f);
                    l1.setColor(Color.rgb(244, 117, 117));
                    l1.setCubicIntensity(1f);
                    l1.setDrawCircles(true);
                    l1.setCircleRadius(5f);
                    l1.setCircleColor(Color.rgb(244, 117, 117));
                    l1.setCircleColorHole(Color.rgb(244, 117, 117));
                    l1.setDrawValues(true);
                    l1.setValueTextSize(12f);
                    l1.setValueFormatter(new IValueFormatter() {
                        @Override
                        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                            F.w("value : " + value + "dataSetIndex : " + dataSetIndex);
                            if (entry.getX() == 0) {
                                return "  " + String.valueOf(value);
                            } else if (entry.getX() == (o.size() - 1)) {
                                return String.valueOf(value) + "               ";
                            } else {
                                return "";
                            }
                        }
                    });
                    List<ILineDataSet> lineDataSetArrayList = new ArrayList<>();
                    //设置曲线展示为圆滑曲线（如果不设置则默认折线）
                    lineDataSetArrayList.add(l1);
                    LineData lineData = new LineData(lineDataSetArrayList);
                    lineView.setDrawGridBackground(false);
                    lineView.setDrawBorders(false);
                    lineView.setGridBackgroundColor(R.color.transparent);
                    lineView.setData(lineData);
                    lineView.setExtraRightOffset(XYBAUtils.dip2px(8));
                    lineView.setExtraLeftOffset(XYBAUtils.dip2px(8));
                    lineView.animateXY(800, 800);
                    lineView.setScaleMinima(1f, 1f);
                } catch (Exception e) {
                    e.printStackTrace();
                    lineView.setVisibility(View.GONE);
                }
            }
        }
    }

    private void initStockView(final UserAccount user) {
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                if (user == null) {
                    return;
                }

                if (tvAcount != null) {
                    tvAcount.setNumberString(StringUtil.isEmpty(user.getAccount()) ? "0.00000000" : user.getAccount());
                }

                stockPrice = user.getStockPrice();
                if (tvGuPrice != null) {
                    tvGuPrice.setNumberString(stockPrice, StringUtils.isEmpty(user.getStockPrice()) ? "0" : user.getStockPrice());
                }

                if (tvGuNum != null) {
                    tvGuNum.setNumLength(4);
                    tvGuNum.setNumberString(StringUtil.isEmpty(user.getStockCount()) ? "0.0000" : new BigDecimal(user.getStockCount()).setScale(4, RoundingMode.UP).toPlainString());
                }
            }
        }, 500);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void consumeHomeRxBeanEvent(HomeRxBean homeRxBean) {
        if (homeRxBean.getStatus() == HomeRxBean.USER_ACCOUNT) {
            UserAccount userAccount = (UserAccount) homeRxBean.getBean();
            updateView();
            initStockView(userAccount);
            if (user.getTaskUnRevice()) {
                taskHint.setVisibility(View.VISIBLE);
            } else {
                taskHint.setVisibility(View.GONE);
            }
        } else if (homeRxBean.getStatus() == HomeRxBean.TASK_EVENT) {
            TaskNewEvent taskNewEvent = (TaskNewEvent) homeRxBean.getBean();
            if (taskNewEvent.isTaskUnRevice()) {
                taskHint.setVisibility(View.VISIBLE);
            } else {
                taskHint.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Bus bus = RxBus.get();
        if (bus.hasRegistered(this)) {
            bus.unregister(PacketFragment.this);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_packet;
    }


}
